from django.utils.deprecation import MiddlewareMixin
from aj import models
from django.shortcuts import redirect
import re
import json


class MyAuth(MiddlewareMixin):
    def process_request(self, request):
        white_list = ['/login/\d+/', '/regist/', '/admin/']  # 白名单
        next_url = request.path_info
        user_id = request.session.get("user_id")
        # 在白名单的
        for valid_url in white_list:
            ret = re.match(valid_url, next_url)
            if ret:
                return None
        # 已登陆的
        if user_id:
            request.user = models.UserInfo.objects.filter(id=user_id).first()
            # yhlb = user_obj.category  # 类别 1管理员 2普通用户
            # yhjb = user_obj.level  # 级别1省级 2市级 3县级
            # # 如果是用户就查询自己本身的，如果是管理员，就把管理员下面的用户id列表赋值给request
            # cxtj = request.session.get("cxtj", None)
            # request.cxtj = []
            # user_list = []
            # if not yhlb == "2":
            #     if cxtj:
            #         request.cxtj = json.loads(cxtj)
            #         return None
            #     if yhjb == "1":  # 省级管理员
            #         user_list = models.UserInfo.objects.filter(
            #             organization__xingzhengquhua__sheng=user_obj.organization.xingzhengquhua.sheng).values_list("id", flat=True)
            #     elif yhjb == "2":
            #         user_list = models.UserInfo.objects.filter(
            #             organization__xingzhengquhua__shi=user_obj.organization.xingzhengquhua.shi).values_list("id",flat=True)
            #     elif yhjb == "3":
            #         user_list = models.UserInfo.objects.filter(
            #             organization__xingzhengquhua__xian=user_obj.organization.xingzhengquhua.xian).values_list("id",flat=True)
            #     elif yhjb == "4":
            #         user_list = models.UserInfo.objects.filter(xiang=user_obj.xiang).values_list("id", flat=True)
            #     request.cxtj = user_list
            #     request.session["cxtj"] = json.dumps(list(user_list))
            return None
        # 未登录的
        if '/1/'in request.path_info:
            return redirect("/login/1/?next={}".format(next_url))
        else:
            return redirect("/login/2/?next={}".format(next_url))
